//
//  HomePageTableViewController.m
//  GaoBiaoB
//
//  Created by lanou3g on 16/1/15.
//  Copyright © 2016年 lanou3g. All rights reserved.
//
#import "HomePageTableViewController.h"
#import "HomeTableViewCell.h"
#import "HomePageDataManager.h"
#import "SDCycleScrollView.h"
#import "UIImageView+WebCache.h"
#import "XuanCityTableViewController.h"
#import "SmallCity.h"
#import "CategoryTableViewController.h"
#import "Nuomishuo.h"
#import "ChaShop.h"
#import "ChaXtuan.h"
#import "XiangViewController.h"
#include <AVOSCloud/AVOSCloud.h>
@interface HomePageTableViewController ()<SDCycleScrollViewDelegate>
//展示轮播图的家伙
@property(nonatomic,strong)UIView *headerView;
//接收数据
@property (nonatomic,strong)NSMutableArray *otherArray;

//展示店面列表信息
@property(nonatomic,strong)NSMutableArray * listArray;
@property(nonatomic,strong)NSMutableDictionary *listDict;

@end

//重用标识
NSString *cellIdentifier = @"homePageCell";
@implementation HomePageTableViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self basicSetUp];
    [self aHeaderView];
    [self requestNet];

    //自定义cell注册
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
    
    [[Nuomishuo alloc]init].upData = ^(){
        [self.tableView reloadData];
    };
}
//基础信息设置ß
-(void)basicSetUp{
    self.view.backgroundColor = [UIColor whiteColor];

    self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-erweima"] style:UIBarButtonItemStyleDone target:self action:@selector(qrCodeDidClicked:)],[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-gouwuche"] style:UIBarButtonItemStyleDone target:self action:@selector(shoppingCarDidClicked:)]];

    self.navigationItem.leftBarButtonItems = @[[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-xiao"] style:UIBarButtonItemStyleDone target:self action:@selector(citySelect:)]];
}
//点击左侧按钮跳转到城市选择页面
-(void)citySelect:(UIBarButtonItem *)sender{
    XuanCityTableViewController *city = [[XuanCityTableViewController alloc]initWithStyle:UITableViewStyleGrouped];
    [self.navigationController pushViewController:city animated:YES];
}
//上部视图
-(void)aHeaderView{
    self.headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width/2+30)];
    _headerView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = _headerView;
    [self createView];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(_headerView.frame)-30, 100, 50)];
    label.textColor = [UIColor orangeColor];
//    label.backgroundColor =[UIColor purpleColor];
    label.text = @"猜你喜欢";
    [_headerView addSubview:label];
}
//轮播图下面类目选择
-(void)createView{
    NSArray *array = @[@"http://timg.baidu.com/timg?lbstsm&ref=http%3a%2f%2fbj.nuomi.com&quality=100&size=8&sec=1453269958&di=9106f9a5541a4255368ec8ef67099178&src=http://e.hiphotos.baidu.com/bainuo/crop=0,0,720,436;w=720;q=99/sign=4f4db215a444ad343af0ddc7ed9220c4/f703738da97739126d759599fd198618377ae2f3.jpg",@"http://timg.baidu.com/timg?lbstsm&ref=http%3a%2f%2fbj.nuomi.com&quality=100&size=8&sec=1453269958&di=d16965860ea16a4adef477511e67973a&src=http://e.hiphotos.baidu.com/bainuo/crop=0,82,756,459;w=470;q=89/sign=73f4918d15dfa9ece9610c575fe0db3b/6a600c338744ebf89b6b97aeddf9d72a6059a70d.jpg",@"http://timg.baidu.com/timg?lbstsm&ref=http%3a%2f%2fbj.nuomi.com&quality=100&size=8&sec=1453269958&di=85e5b5264161c859b0c0dc34186720fa&src=http://e.hiphotos.baidu.com/bainuo/crop=0,0,720,436;w=720;q=79/sign=36b1788e4d36acaf4dafccbc41e9a120/dbb44aed2e738bd44e428986a78b87d6277ff922.jpg"];
    CGFloat x = self.view.bounds.size.width;
     SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, x, self.headerView.frame.size.height-30) imageURLStringsGroup:nil]; // 模拟网络延时情景
     cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
     cycleScrollView2.delegate = self;
     cycleScrollView2.dotColor = [UIColor yellowColor]; // 自定义分页控件小圆标颜色
     cycleScrollView2.placeholderImage = [UIImage imageNamed:@"placeholder"];
     [self.headerView addSubview:cycleScrollView2];
    
     //             --- 模拟加载延迟
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
     cycleScrollView2.imageURLStringsGroup = array;
     });
}
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"---点击了第%ld张图片", index);
}
//点击购物车触发事件 ========== 扫描二维码触发事件
-(void)shoppingCarDidClicked:(UIBarButtonItem *)sender{
    
}
-(void)qrCodeDidClicked:(UIBarButtonItem *)sender{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return _listArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [_listDict[_listArray[section]]count];
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *array = _listDict[_listArray[indexPath.section]];
    ChaXtuan *model = array[indexPath.row];
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.homePageNameLabel.text = model.min_title;
    cell.homePagePriceLabel.text = [NSString stringWithFormat:@"￥ %d",model.current_price/100];
    [cell.homepageImageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:[UIImage imageNamed:@"iconfont-tu"]];
    cell.homePageDistanceLabel.text = [NSString stringWithFormat:@"%d人已购买",model.sale_num];
    cell.descripTionLabel.text = model.Description;
    return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return _listArray[section];
}

//点击之后跳转到详情页面
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    XiangViewController *xiang = [[XiangViewController alloc]init];
    NSArray *array = _listDict[_listArray[indexPath.section]];
    ChaXtuan *model = array[indexPath.row];
    xiang.urlStr =model.deal_url;
    NSLog(@"%@",model.deal_url);
    [self.navigationController pushViewController:xiang animated:YES];
}
-(void)requestNet{
    if (_midCityID == nil ) {
        _midCityID = @"100010000";
    }
    if (_smallCityID == nil ) {
        _smallCityID = @"394,395";
    }
    NSString *httpStr = @"http://apis.baidu.com/baidunuomi/openapi/searchshops";
    NSString *urlStr = [NSString stringWithFormat:@"city_id=%@&cat_ids=&subcat_ids=&district_ids=&bizarea_ids=&location=&keyword=&radius=&page=&page_size=100&deals_per_shop=",_midCityID];
    Nuomishuo *nuo= [[Nuomishuo alloc]init];
        [nuo request:httpStr withHttpArg:urlStr];
        _otherArray = [NSMutableArray array];
        __weak typeof(nuo)temp = nuo;
        dispatch_async(dispatch_get_main_queue(), ^{
            temp.upData=^(){
                _otherArray = nuo.array;
                for (ChaShop * cha in temp.array) {
                    NSString *key = cha.shop_name;
                    for (NSDictionary *small in cha.deals) {
                        ChaXtuan *model = [ChaXtuan new];
                        [model setValuesForKeysWithDictionary:small];
                        //要是组不存在那么重新创建
                        if (self.listDict[key] == nil) {
                            NSMutableArray *groupArray = [NSMutableArray array];
                            [groupArray addObject:model];
                            [self.listDict setObject:groupArray forKey:key];
                        }else{
                            NSMutableArray *groupArray = self.listDict[key];
                            [groupArray addObject:model];
                        }
                    }
                }
                self.listArray = [NSMutableArray arrayWithArray:_listDict.allKeys];
                [self.tableView reloadData];
            };
        });
}
-(NSMutableDictionary *)listDict{
    if (_listDict == nil) {
        _listDict = [NSMutableDictionary dictionary];
    }
    return _listDict;
}
@end
